package net.androidla.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketActivity extends Activity {
	private EditText ipStr;
	private EditText portStr;
	private EditText msgStr;
	private TextView serverStr;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(onClickListener);
        ipStr = (EditText) findViewById(R.id.ipStr);
        portStr = (EditText) findViewById(R.id.portStr);
        msgStr = (EditText) findViewById(R.id.msgStr);
        serverStr = (TextView) findViewById(R.id.serverStr);
    }
    
    private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			new Thread(new TCPAndroidClient()).run();
		}
	};
	
	class TCPAndroidClient implements Runnable {
		String ip = ipStr.getText().toString().trim();
		String port = portStr.getText().toString().trim();
		String msg = msgStr.getText().toString().trim();
		@Override
		public void run() {
			try {
			    Socket s = new Socket(ip, Integer.parseInt(port));
			    PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
			    pw.println(msg);
			    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			    serverStr.setText(br.readLine());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}